/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tabox.server;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rendy
 */
public class Database {
    private static Database db = new Database();
    
    String dbURL = "jdbc:mysql://localhost/tabox";
    String user = "root";
    String pswd = "";
    
    Connection connection;
    Statement statement;
    
    public void connect(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = (Connection) DriverManager.getConnection(dbURL, user, pswd);
            statement = (Statement) connection.createStatement(1004,1008);
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public ResultSet query(String q){
        ResultSet rs = null;
        try {
            rs = statement.executeQuery(q);
        } catch (SQLException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rs;
    }
    
    public void insert(String q) throws SQLException{
        statement.executeUpdate(q);
    }
    
    public void close(){
        try {
            connection.close();
        } catch (SQLException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static Database getSingleton(){
        return db;
    }
    
    
    public Boolean checkLogin(String username, String password) throws SQLException{        
	connect();
        ResultSet rs = query("select * from user where username='"+username+"'");
        int n = 0;
        String pswd = "";
        while(rs.next()){
            pswd = rs.getString("password");
            n++;
        }
        close();
        if(n==0){
            return false;
        } else {
            return password.equals(pswd);
        }
    }
    
    public static void main (String[] args) throws SQLException{
        Database db = new Database();
        System.out.println("login "+db.checkLogin("rendy","rendy"));
    }
}